import {
    axios
} from '../../../../utils/ajax.js';
import {
    gettime
} from '../../../../utils/djs.js';
let app = getApp()
let shareImg;

Page({
    data: {
        iPhoneX: false,
        //页面颜色尺码展示区域
        targetColor: [],
        targetSkusize: [],
        //可查资源处
        specData: [],
        //遮罩层状态
        maskstate: false,
        //购买弹窗
        goodsboxshow: false,
        //库存
        stock: '',
        //已经选择的颜色
        colorchecked: '',
        //已经选择的尺码
        skuchecked: '',
        //选择的数量
        nowstock: 1,
        //当前选中规格商品的库存
        checkedstock: '',
        //当前选中规格的id
        specId: '',
        //弹窗的商品默认图片
        defaultimg: '',
        goodsbigimg: '',
        //商品弹窗顶部显示的价格 
        goodsboxprice: '',
        goodsId: ''
    },

    onLoad: function(options) {
        if (app.globalData.model.substr(0, 8) == 'iPhone X') {
            this.setData({
                iPhoneX: true
            })
        }
        console.log('options:', options)
        this.setData({
            groupId: options.groupId ? options.groupId : 0
        })
        this.getGroupData()
        this.getLikeData()
    },

    getGroupData: function() {
        axios({
            url: '/group/groupDetail',
            data: {
                groupId: this.data.groupId,
                userid: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').userid : null,
                token: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').token : null,
            }
        }).then(res => {
            console.log(res.data)
            if (res.data.goodsInfo) {
                //重新组合页面展示区域颜色规格数据结构
                let specShow = new Array(res.data.goodsInfo.specShow.color.length)
                for (let i = 0; i < res.data.goodsInfo.specShow.color.length; i++) {
                    specShow[i] = {}
                    specShow[i].val = res.data.goodsInfo.specShow.color[i]
                    specShow[i].cansell = true,
                        specShow[i].checked = false
                }
                let skusize = new Array(res.data.goodsInfo.specShow.skusize.length)
                for (let i = 0; i < res.data.goodsInfo.specShow.skusize.length; i++) {
                    skusize[i] = {}
                    skusize[i].val = res.data.goodsInfo.specShow.skusize[i]
                    skusize[i].cansell = true
                    skusize[i].checked = false
                }
                this.setData({
                    defaultimg: res.data.goodsInfo.goodsImg,
                    goodsbigimg: res.data.goodsInfo.goodsImg,
                    targetColor: specShow,
                    targetSkusize: skusize,
                    specData: res.data.goodsInfo.specData,
                    goodsboxprice: res.data.goodsInfo.groupPriceRange,
                    goodsId: res.data.goodsInfo.goodsId
                })
                console.log(this.data.specData)
            }

            let qArr = new Array();
            qArr.length = res.data.groupInfo.quota > 0 ? res.data.groupInfo.quota : null
            this.setData({
                data: res.data,
                qArr: qArr
            })

            this.drawShareImg()

            // 倒计时
            let closetime = this.data.data.groupInfo.times;
            this.setData({
                countdown: gettime(closetime, 3).tips,
                overdue: gettime(closetime, 3).tips ? false : true
            })
            let timer = setInterval(() => {
                if (!gettime(closetime, 3)) {
                    clearInterval(timer)
                    this.setData({
                        countdown: false,
                        overdue: true
                    })
                } else {
                    this.setData({
                        countdown: gettime(closetime, 3).tips
                    })
                }
            }, 1000)
        })
    },
    //选择规格
    choosesku(e) {
        if (e.currentTarget.dataset.cansell) {
            let obj = this.data.targetColor
            let curarr = this.data.targetSkusize
            let index = e.currentTarget.dataset.index
            let choosesku = e.currentTarget.dataset.skusize
            if (curarr[index].checked) {
                curarr[index].checked = !curarr[index].checked
            } else {
                curarr.map(function(x) {
                    x.checked = false
                    return x.checked
                })
                curarr[index].checked = !curarr[index].checked
            }
            let result = curarr[index].checked ? this.data.specData.filter(x => x.skusize == choosesku) : this.data.specData
            let skubook = new Array(result.length)
            for (let i = 0; i < result.length; i++) {
                skubook[i] = result[i].color
            }
            obj.forEach((value, index) => {
                if (!skubook.includes(value.val)) {
                    obj[index].cansell = false
                } else {
                    obj[index].cansell = true
                }
            })
            this.setData({
                targetColor: obj,
                targetSkusize: curarr
            })
            this.setData({
                skuchecked: curarr[index].checked ? curarr[index].val : ''
            })
            console.log(this.data.skuchecked)
            this.changeimgprice()
        }
    },
    //根据选择规格的不同改变商品图和价格
    changeimgprice() {
        let specData = this.data.specData
        let result;
        //只有颜色 没有尺码
        if (this.data.targetColor.length && !this.data.targetSkusize.length) {
            result = specData.find(x => x.color == this.data.colorchecked)
            this.setData({
                defaultimg: result.goodsImg ? result.goodsImg : this.data.goodsbigimg,
                goodsboxprice: result.groupPrice,
                specId: result.specId
            })
            //只有尺码 没有颜色
        } else if (!this.data.targetColor.length && this.data.targetSkusize.length) {
            result = specData.find(x => x.skusize == this.data.skuchecked)
            this.setData({
                defaultimg: result.goodsImg ? result.goodsImg : this.data.goodsbigimg,
                goodsboxprice: result.groupPrice,
                specId: result.specId
            })
            //颜色尺码都有
        } else {
            //颜色尺码都选择的话
            if (this.data.colorchecked && this.data.skuchecked) {
                result = specData.find(x => x.color == this.data.colorchecked && x.skusize == this.data.skuchecked)
                this.setData({
                    defaultimg: result.goodsImg ? result.goodsImg : this.data.goodsbigimg,
                    goodsboxprice: result.groupPrice,
                    specId: result.specId
                })
            }
        }
        console.log(result)
    },
    //选择颜色
    choosecolor(e) {
        if (e.currentTarget.dataset.cansell) {
            let obj = this.data.targetSkusize
            let curarr = this.data.targetColor
            let index = e.currentTarget.dataset.index
            let choosecolor = e.currentTarget.dataset.color
            if (curarr[index].checked) {
                curarr[index].checked = !curarr[index].checked
            } else {
                curarr.map(function(x) {
                    x.checked = false
                    return x.checked
                })
                curarr[index].checked = !curarr[index].checked
            }
            let result = curarr[index].checked ? this.data.specData.filter(x => x.color == choosecolor) : this.data.specData
            let colorbook = new Array(result.length)
            for (let i = 0; i < result.length; i++) {
                colorbook[i] = result[i].skusize
            }
            obj.forEach((value, index) => {
                if (!colorbook.includes(value.val)) {
                    obj[index].cansell = false
                } else {
                    obj[index].cansell = true
                }
            })
            this.setData({
                targetSkusize: obj,
                targetColor: curarr
            })
            this.setData({
                colorchecked: curarr[index].checked ? curarr[index].val : ''
            })
            console.log(this.data.colorchecked)
            this.changeimgprice()
        }
    },
    //减法
    sub() {
        let nowstock = this.data.nowstock
        //如果有颜色未选择或者有规格未选择
        if ((this.data.targetColor.length ? !this.data.colorchecked : true) || (this.data.targetSkusize.length ? !this.data.skuchecked : true)) {
            wx.showToast({
                title: '请选择颜色或尺码',
                icon: "none"
            })
        } else {
            //获取选中规格的库存
            this.stockandspecid()
            if (nowstock > 1) {
                nowstock--
                this.setData({
                    nowstock: nowstock
                })
            } else {
                wx.showToast({
                    title: '一件起售',
                    icon: "none"
                })
            }
        }
    },
    //加法
    add() {
        let nowstock = this.data.nowstock
        //如果有颜色未选择或者有规格未选择
        if ((this.data.targetColor.length ? !this.data.colorchecked : true) || (this.data.targetSkusize.length ? !this.data.skuchecked : true)) {
            wx.showToast({
                title: '请选择颜色或尺码',
                icon: "none"
            })
        } else {
            //获取选中规格的库存
            this.stockandspecid()
            if (nowstock < this.data.checkedstock) {
                nowstock++
                this.setData({
                    nowstock: nowstock
                })
            } else {
                wx.showToast({
                    title: '不能大于最大库存',
                    icon: "none"
                })
            }
        }
    },
    //计算选中颜色尺码下的库存和规格id
    stockandspecid() {
        let colorchecked = this.data.colorchecked
        let skuchecked = this.data.skuchecked
        let specData = this.data.specData
        let specId
        let checkedstock
        //如果只有颜色，查颜色
        if (colorchecked && !skuchecked) {
            specId = specData.find(x => x.color == colorchecked).specId
            checkedstock = specData.find(x => x.color == colorchecked).stock
            //如果只有尺码，查尺码
        } else if (skuchecked && !colorchecked) {
            specId = specData.find(x.skusize == skuchecked).specId
            checkedstock = specData.find(x.skusize == skuchecked).stock
            //颜色尺码都查
        } else {
            specId = specData.find(x => x.color == colorchecked && x.skusize == skuchecked).specId
            checkedstock = specData.find(x => x.color == colorchecked && x.skusize == skuchecked).stock
        }
        this.setData({
            specId: specId,
            checkedstock: checkedstock
        })
        console.log('specId:' + specId, 'checkedstock:' + checkedstock)
    },
    //确认用户都选择了 并且关闭商品选择规格弹窗
    confirmgoodsbox() {
        if ((this.data.targetColor.length ? this.data.colorchecked : true) && (this.data.targetSkusize.length ? this.data.skuchecked : true)) {
            this.setData({
                goodsboxshow: false,
                maskstate: false
            })

            //清空购物车数据 因为返回上一级后不保存购物车数据
            wx.removeStorageSync('cartGoods')
            //打印缓存数据
            let cartGoods = wx.getStorageSync('cartGoods')
            console.log(cartGoods)
            let goodsId = cartGoods ? cartGoods.goodsId.split(',') : []
            let specId = cartGoods ? cartGoods.specId.split(',') : []
            let num = cartGoods ? cartGoods.num.split(',') : []
            let goodsCheck = cartGoods ? cartGoods.goodsCheck.split(',') : []
            specId.push(this.data.specId)
            goodsId.push(this.data.goodsId)
            num.push(this.data.nowstock)
            cartGoods = {
                specId: specId.join(),
                goodsId: goodsId.join(),
                num: num.join(),
                goodsCheck: 1,
            }
            //设置缓存
            wx.setStorageSync('cartGoods', cartGoods)
            wx.navigateTo({
                url: `../../../cart/cart?isGroup=1&fightId=${this.data.groupId}`,
            })
        } else {
            wx.showToast({
                title: '请选择颜色尺码',
                icon: "none"
            })
        }
    },
    getLikeData: function() {
        axios({
            url: '/goods/guessLike',
            data: {
                userid: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').userid : null,
                token: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').token : null,
            }
        }).then(res => {
            // console.log(res.data)
            this.setData({
                likelist: res.data.goodslist
            })
        })
    },

    tojoin() {
        this.setData({
            maskstate: true,
            goodsboxshow: true
        })
    },
    //关闭商品选择规格弹窗
    closegoodsbox() {
        this.setData({
            goodsboxshow: false,
            maskstate: false
        })
    },

    onShareAppMessage: function() {
        return {
            title: `【仅剩${this.data.data.groupInfo.quota}个名额】快来${this.data.data.goodsInfo.goodsPrice}元拼${this.data.data.goodsInfo.goodsName}`,
            path: `/pages/home/goodsDetail/grouppage/grouppage?groupId=${this.data.groupId}`,
            imageUrl: shareImg
        }
    },

    drawShareImg: function() {
        const ctx = wx.createCanvasContext('shareCanvas')

        ctx.setFillStyle('#FFF2E8')
        ctx.fillRect(0, 0, 375, 228)

        wx.downloadFile({
            url: this.data.data.goodsInfo.goodsImg,
            success: goodsImg => {
                if (goodsImg.statusCode === 200) {

                    ctx.drawImage(goodsImg.tempFilePath, 13, 13, 202, 202)

                    ctx.setFontSize(25)
                    ctx.setFillStyle('#C8431A')
                    ctx.fillText('￥', 235, 55)

                    ctx.setFontSize(36)
                    ctx.fillText(this.data.data.goodsInfo.groupPrice, 255, 55)

                    ctx.setFontSize(12)
                    ctx.setFillStyle('#9B9B99')
                    ctx.fillText('￥' + this.data.data.goodsInfo.shopPrice, 240, 76)

                    ctx.beginPath()
                    ctx.moveTo(241, 72)
                    ctx.lineTo(251 + 9 * (this.data.data.goodsInfo.shopPrice.length), 72)
                    ctx.setStrokeStyle('#9B9B99')
                    ctx.stroke()

                    ctx.setFontSize(13)
                    ctx.setFillStyle('#C8431A')
                    ctx.fillText('限时立省￥' + this.data.data.goodsInfo.savemoney, 240, 102)

                    let masterAvatar = this.data.data.groupInfo.groupList.find(item => item.isMaster == 1).userImg;

                    wx.downloadFile({
                        url: masterAvatar,
                        success: masterAvatar => {
                            if (masterAvatar.statusCode === 200) {
                                
                                ctx.drawImage(masterAvatar.tempFilePath, 258, 125, 30, 30)

                                ctx.drawImage('/images/home/ab.png', 253, 120, 38, 38)

                                ctx.drawImage('/images/home/q.png', 304, 124, 32, 32)

                                ctx.drawImage('/images/home/shareb1.png', 238, 170, 116, 34)
                                ctx.setFontSize(17)
                                ctx.setFillStyle('#fff')
                                ctx.fillText('立即拼团', 262, 193)

                                ctx.drawImage('/images/home/share_line.png', 0, 256, 375, 22)

                                ctx.setFontSize(17)
                                ctx.setFillStyle('#DE833D')
                                ctx.fillText('有品质的拼团App', 122, 274)

                                ctx.draw(true, () => {
                                    wx.canvasToTempFilePath({
                                        x: 0,
                                        y: 0,
                                        width: 375,
                                        height: 310,
                                        canvasId: 'shareCanvas',
                                        success: res => {
                                            shareImg = res.tempFilePath
                                            console.log('shareImg:', shareImg)
                                        }
                                    })
                                })
                            }
                        }
                    })
                }
            }
        })

    }
})